﻿using MSL.Tool;
using MSL.Tool.Data;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows;
using TimedTask.Core;
using TimedTask.Models;
using TimedTask.Tools;

namespace TimedTask
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        //单实例运行代码
        Mutex mutex;
        //应用程序启动前调用
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            bool createdNew;
            mutex = new Mutex(true, Const.ApplicationName, out createdNew);
            if (!createdNew)
            {
                MessageBox.Show("程序已经启动！");
                Environment.Exit(0);
            }
            //if (e.Args.Length > 0)//启动参数
            OnInit();
            DoTask();
        }

        //系统初始化
        private void OnInit()
        {
            Const.StartPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            Const.Config = Const.StartPath + "\\Config.xml";
            //日志文件夹
            LogHelper.LogPath = Const.StartPath + "\\Log\\";
            IOHelper.CreateFolder(LogHelper.LogPath);

            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Application_Error);//注册全局Application_Error
            //读取配置
            Helper.ReadConf();
        }

        /// <summary>
        /// 运行任务
        /// </summary>
        private void DoTask()
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                NotifyIconHelper.Instance();
                //NotifyIconHelper.Instance().ShowBalloonTip("提示", "程序运行成功！");

                BLL.SysLogBLL taskLog = new BLL.SysLogBLL();
                IOHelper.DeleteFiles(LogHelper.LogPath, new string[] { ".txt", ".log" }, 4);//删除4天前日志文件
                taskLog.DeleteHistory();

                //20 秒轮询任务
                ATimer.setInterval(20000, () =>
                {
                    TaskManager.StartTask();
                });
            }));
        }
        /// <summary>
        /// 系统关机前调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
        {
            base.OnSessionEnding(e);
        }
        /// <summary>
        /// 应用程序关闭前调用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
        }
        /// <summary>
        /// 全局异常处理逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_Error(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            LogHelper.SaveLog("异常信息", e.Exception.Source + "\r\n" + e.Exception.Message);
            e.Handled = true;//处理完后，我们需要将Handler=true表示已此异常已处理过
        }
        /// <summary>
        /// 捕获关机 - 不起作用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
        {
            e.Cancel = true;//阻止关机
            // Ask the user if they want to allow the session to end
            string msg = string.Format("{0}. End session?", e.ReasonSessionEnding);
            MessageBoxResult result = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo);

            // End session, if specified
            if (result == MessageBoxResult.No)
            {
                e.Cancel = true;
            }
        }
    }
}
